<template>
  <div id="cesiumContainer"></div>
  <!-- 气泡HTML -->
  <div id="bubble1" class="bubble" v-show="poiShow">
    <button class="closePopup" @click="close">×</button>
    <el-table :data="tableData">
      <el-table-column fixed prop="key" label="属性" />
      <el-table-column prop="value" label="数值" />
    </el-table>
  </div>
</template>

<script>
/* eslint-disable */
import { onMounted, getCurrentInstance } from "@vue/runtime-core";
import widget from "../../Widgets/widgets.css";
import url from "@/components/URL.json";
import pubsub from "pubsub-js";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import axios from "axios";
import "@/components/WallDiffuseMaterialProperty.js";
import { ElMessage } from "element-plus";
import * as cesiumApi from "@/api/cesiumApi.js";

import net from "@/json/大同村网格0803.json";
import supplyRange from "@/json/供电范围1226.json";
import buildingPosition from "@/json/大同村房屋面1128.json";
import 国有土地 from "@/json/国有土地.json";
// import 基本农田 from "@/json/基本农田.json";
import 基本农田 from "@/json/大同村基本农田.json";
import 合流污水管 from "@/json/合流污水管.json";
import 现状污水管 from "@/json/现状污水管.json";
import 现状雨水管 from "@/json/现状雨水管.json";
import 新建污水管 from "@/json/新建污水管.json";
import 新建雨水管 from "@/json/新建雨水管.json";
import transformerJSON from "@/json/变压器点位1130.json";
import buildingJSON from "@/json/大同村房屋面1129.json";
import recommendJSON from "@/json/变电站推荐1130.json";
import supplyLineJSON from "@/json/供电线路.json";
// import loadCapacityJSON from "@/json/负荷推演试点1215.json";
import loadCapacityJSON from "@/json/负荷推演房屋面1222.json";
// import recommendResult from "@/json/推荐结果.json";
// import recommendLayer from "@/json/要素整合.json";
import recommendResult from "@/json/推荐结果0229.json";
import recommendLayer from "@/json/要素整合0229.json";

export default {
  name: "map",
  data: () => {
    return {
      title: "示例标题",
      imgPath: "暂无图片.png",
      hoverIMG: false,
      colorIndex: 0,
      subList: [],
      tipShow: false,
      buildingSelected: {},
      peopleID: "",
      treeShow: false,
      button1Show: false,
      button2Show: false,
      poi: "",
      poiShow: false,
      poiShow1: false,
      tableData: [],
      villageIntroductionShow: false,
      specialPeopleData: [],
      IRshow: false,
    };
  },
  setup() {
    const { proxy } = getCurrentInstance();
    const router = useRouter();
    const store = useStore();
    let scene, promise, handlerPolygon, modelLayer;
    // arcgisserver服务图层
    let serverLayer;
    // 地图操作器
    let handler,
      handlerBillborad,
      handlerSpecialPeople,
      handlerEnterprise,
      handlerIdentifyPolygon,
      handlerIdentifyPolyline,
      handlerTransformer,
      handlerRecommend,
      handlerHouseLoad,
      handlerLanduse;

    let identifyPolygonFlag = false;
    let identifyPolylineFlag = false;
    let clickReady = false;
    let positions = [],
      regions = [];
    let isBuildingSelected = false;
    let scenePosition = {};
    let poiList = [];
    let transformerList = [];
    let buildingclicking = false;
    let transformerClick = false;
    let buildingCenter = {};
    let lableHeight = 30;
    let moveFlag = true;
    let specialPeopleList = [];
    let JSONList = {
      国有土地,
      基本农田,
      合流污水管,
      现状污水管,
      现状雨水管,
      新建污水管,
      新建雨水管,
    };
    let PolygonShowedList = [];
    let PolylineShowedList = [];
    let currentPosition = {
      lat: 0,
      lon: 0,
      height: 0,
    };
    let maskON = false;
    // 配色列表
    let colorList = [
      "#1296db",
      "#f89407",
      "#83c6c2",
      "#d81e06",
      "#02bb5c",
      "#d4237a",
      "#4f68b0",
      "#8a8a8a",
      "#13227a",
      "#7a1103",
      "#2c2c2c",
      "#9f05fa",
    ];
    let needCut = true;
    // 推荐拿地参考面集合
    let layerList = [
      {
        features: [],
        name: "集体用地",
        layer: {},
      },
      {
        features: [],
        name: "交通道路",
        color: "#212529",
        layer: {},
      },
      {
        features: [],
        name: "水系范围",
        color: "#26b7ff",
        layer: {},
      },
      {
        features: [],
        name: "基本农田",
        color: "#f4ea2a",
        layer: {},
      },
      // {
      //   features: [],
      //   name: "居民房屋",
      //   color: "#f89407",
      // layer: {},
      // },
    ];
    // 推荐结果
    let resultLayer = new Array(0);

    onMounted(() => {
      // 启动
      onload(Cesium);
      // 消息订阅合集
      subscribeList();
      // 实时记录中心坐标
      centerPositionRecord();
    });

    // 实时记录中心坐标
    function centerPositionRecord() {
      viewer.scene.postRender.addEventListener(function () {
        var cameraPostion = viewer.scene.camera.position;
        var centerCartographic =
          scene.globe.ellipsoid.cartesianToCartographic(cameraPostion);
        let lat = Cesium.Math.toDegrees(centerCartographic.latitude);
        let lon = Cesium.Math.toDegrees(centerCartographic.longitude);
        let height = centerCartographic.height;
        if (
          lat != currentPosition.lat ||
          lon != currentPosition.lon ||
          height != currentPosition.height
        ) {
          // console.log("中心坐标发生改变");
          // console.log("经度" + lon, "纬度" + lat, "高度" + height);
          currentPosition.lat = lat;
          currentPosition.lon = lon;
          currentPosition.height = height;
        }
      });
    }

    // 消息订阅合集
    function subscribeList() {
      proxy.subList[0] = pubsub.subscribe("buildingSelected", (n, data) => {
        if (needCut) {
          // console.log(data);
          isBuildingSelected = true;
          showBuilding(data);
          buildingCenter = {
            x: data.attributes["X"],
            y: data.attributes["Y"],
          };
        }
      });
      proxy.subList[1] = pubsub.subscribe("cutByNet", (n, data) => {
        console.log(data);
        // 去除当前裁剪操作
        for (var layer of modelLayer) {
          layer.clearModifyRegions();
        }
        setTimeout(() => {
          cutByNet(data);
        }, 500);
      });
      proxy.subList[2] = pubsub.subscribe("needReturn", (n, data) => {
        if (needCut) {
          proxy.buildingSelected = {};
          // 清除楼栋掩膜
          let entities = viewer.entities._entities._array;
          for (let i = 0; i < entities.length; i++) {
            if (
              entities[i]._name != undefined &&
              entities[i]._name != "村委会标识"
            ) {
              viewer.entities.remove(entities[i]);
              i--;
            }
          }
          // 视图定位
          initCamera();
        }
      });
      proxy.subList[3] = pubsub.subscribe("peopleSelected", (n, data) => {
        if (needCut) {
          // console.log(data);
          isBuildingSelected = false;
          // 按距离匹配楼栋
          let nearestBuilding = matchByDistance(
            data.location_x,
            data.location_y
          );
          //显示单体楼栋;
          showBuilding(nearestBuilding);
        } else {
          console.log("楼栋已选择");
        }
      });
      proxy.subList[4] = pubsub.subscribe("clickTipShow", (n, data) => {
        data ? clickBuildingOn() : clickBuildingOff();
      });
      proxy.subList[5] = pubsub.subscribe("netCut", (n, data) => {
        proxy.tipShow = !data;
        if (proxy.tipShow) {
          //清除网格线
          viewer.entities.removeAll();
          drawToCut();
          clickMap();
        } else {
          handlerPolygon.deactivate();
          pubsub.publish("needReturn", "@");
        }
      });
      proxy.subList[6] = pubsub.subscribe("POIshowOn", (n, data) => {
        addPOI(data);
        // 点击事件
        clickMap();
      });
      proxy.subList[7] = pubsub.subscribe("POIshowOff", (n, data) => {
        // 最后一类poi
        if (proxy.colorIndex === 0) {
          // 关闭点击
          clickReady = false;
          handlerBillborad.destroy();
        }
        // 重置颜色
        if (proxy.colorIndex > 0) {
          proxy.colorIndex -= 1;
        }
        // 删除标识
        deletePOI(data);
        proxy.poiShow = false;
      });
      proxy.subList[8] = pubsub.subscribe("addOneFacility", (n, data) => {
        // 点击事件
        clickMap();
        poiList = [data];
        // 关闭当前单个选中设施
        deletePOI("单个设施选中");
        // 开启新的单个选中设施
        let imgURL = require("../../assets/pic2/icon/" +
          colorList[0].split("#")[1] +
          ".png");
        poiIconLabelAdd(
          Number(data["84Lng"]),
          Number(data["84Lat"]),
          data["LB"],
          colorList[0],
          imgURL,
          "单个设施选中" + data["LB"]
        );
      });
      proxy.subList[9] = pubsub.subscribe("facilityTableShow", (n, data) => {
        if (!data) {
          deletePOI("单个设施选中");
        }
      });
      proxy.subList[10] = pubsub.subscribe("addBufferPOI", (n, data) => {
        // 添加poi
        addPOIList(data);
        // 点击事件
        clickMap();
        // 视图移动
        let x = Number(buildingCenter.x);
        let y = Number(buildingCenter.y) - 0.002;
        console.log(buildingCenter);
        scene.camera.flyTo({
          destination: Cesium.Cartesian3.fromDegrees(x, y, 120),
          orientation: {
            heading: 4.4231285301066237e-13,
            pitch: -0.5,
            roll: 0,
          },
        });
      });
      proxy.subList[11] = pubsub.subscribe("deleteBufferPOI", (n, data) => {
        console.log(data);
        data.forEach((element) => {
          deletePOI(element["LB"]);
        });
        proxy.poiShow = false;
      });
      proxy.subList[12] = pubsub.subscribe("cameraRotation", (n, data) => {
        // 获取当前地图中心的经纬度
        let centerResult = viewer.camera.pickEllipsoid(
          new Cesium.Cartesian2(
            viewer.canvas.clientWidth / 2,
            viewer.canvas.clientHeight / 2
          )
        );
        // 视角中心坐标
        let curPosition =
          Cesium.Ellipsoid.WGS84.cartesianToCartographic(centerResult);
        // 中心经纬度坐标
        let lng = (curPosition.longitude * 180) / Math.PI;
        let lat = (curPosition.latitude * 180) / Math.PI;
        // 生成坐标
        let point1 = Cesium.Cartographic.fromDegrees(lng, lat);
        let point2 = Cesium.Cartographic.fromDegrees(
          currentPosition.lon,
          currentPosition.lat
        );
        let position1 = Cesium.Cartesian3.fromRadians(
          point1.longitude,
          point1.latitude,
          25
        );
        let position2 = Cesium.Cartesian3.fromRadians(
          point2.longitude,
          point2.latitude,
          currentPosition.height
        );
        let distance = Cesium.Cartesian3.distance(position1, position2);
        // console.log(distance);
        if (data === "on") {
          viewer.clock.onTick.addEventListener(
            rotateCamera(lng, lat, distance)
          );
        } else {
          viewer.clock.stopTime = viewer.clock.startTime;
          // location.reload();
        }
      });
      proxy.subList[13] = pubsub.subscribe("respawnPOI", (n, data) => {
        poiList.forEach((poi) => {
          if (poi.LB === data) {
            let imgURL = require("../../assets/pic2/icon/" +
              colorList[proxy.colorIndex].split("#")[1] +
              ".png");
            poiIconLabelAdd(
              Number(poi["84Lng"]),
              Number(poi["84Lat"]),
              poi["LB"],
              colorList[proxy.colorIndex],
              imgURL
            );
          }
        });
        proxy.colorIndex += 1;
      });
      proxy.subList[14] = pubsub.subscribe("toPOI", (n, data) => {
        proxy.poiShow = false;
        // 开启billborad点击事件
        clickMap();
        // 视角移动
        scene.camera.flyTo({
          destination: Cesium.Cartesian3.fromDegrees(
            Number(data["84Lng"]),
            Number(data["84Lat"]) - 0.00005,
            100
          ),
          orientation: {
            heading: 4.4231285301066237e-13,
            pitch: -1.5,
            roll: 0,
          },
        });
      });
      proxy.subList[15] = pubsub.subscribe("needCut", (n, data) => {
        needCut = data;
      });
      proxy.subList[16] = pubsub.subscribe("netView", () => {
        scene.camera.flyTo({
          destination: Cesium.Cartesian3.fromDegrees(113.5425, 22.802, 150),
          orientation: {
            heading: 0.5,
            pitch: -0.4,
            roll: 0,
          },
        });
      });
      proxy.subList[17] = pubsub.subscribe("netPOI", (n, data) => {
        setTimeout(() => {
          // 添加poi
          addPOIList(data);
        }, 500);
      });
      proxy.subList[18] = pubsub.subscribe("hierarchyQuit", () => {
        let entities = viewer.entities._entities._array;
        for (let i = 0; i < entities.length; i++) {
          if (
            entities[i]._name != undefined &&
            entities[i]._name.indexOf("网格") != -1
          ) {
            viewer.entities.remove(entities[i]);
            i--;
          }
        }
      });
      proxy.subList[19] = pubsub.subscribe("netChange", (n, data) => {
        //去除原有网格线
        let entities = viewer.entities._entities._array;
        for (let i = 0; i < entities.length; i++) {
          if (
            entities[i]._name != undefined &&
            entities[i]._name.indexOf("网格") != -1
          ) {
            viewer.entities.remove(entities[i]);
            i--;
          }
        }
        // 是否有新的
        if (data.new) {
          console.log(net.features);
          net.features.forEach((element) => {
            if (element.attributes.name === data.net) {
              // 视角定位
              scene.camera.flyTo({
                destination: Cesium.Cartesian3.fromDegrees(
                  element.attributes.x -
                    (data.net === "重点示范区" ? 0 : 0.0005),
                  element.attributes.y,
                  data.net === "重点示范区" ? 200 : 1000
                ),
                orientation: {
                  heading: 0,
                  pitch: Cesium.Math.toRadians(-90),
                  roll: 0,
                },
                duration: 2,
              });
              // 绘制新网格线
              var points = new Array(0);
              element.geometry.rings[0].forEach((point) => {
                points.push(point[0]);
                points.push(point[1]);
              });
              viewer.entities.add({
                id: element.attributes.name,
                name: "网格线",
                polygon: {
                  hierarchy: Cesium.Cartesian3.fromDegreesArray(points),
                  material: new Cesium.Color(1.0, 0.0, 0.0, 0.7),
                  outline: true,
                  outlineColor: Cesium.Color.RED,
                  outlineWidth: 5,
                  extrudedHeight: 15,
                  closeBottom: false,
                  closeTop: false,
                  classificationType: Cesium.ClassificationType.S3M_TILE,
                },
              });
            }
          });
        }
      });
      proxy.subList[20] = pubsub.subscribe("hoverBuildingIn", (n, building) => {
        // 绘制
        let centerX = building.attributes["x"];
        let centerY = building.attributes["y"];
        // 扩展角点
        let expand = 0.00002;
        let points = [];
        building.geometry.rings[0].forEach((element) => {
          let x = element[0];
          let y = element[1];
          centerX < x ? (x = x + expand) : (x = x - expand);
          centerY < y ? (y = y + expand) : (y = y - expand);
          points.push(x, y);
        });
        // 清除高亮掩膜
        let entities = viewer.entities._entities._array;
        for (let i = 0; i < entities.length; i++) {
          if (
            entities[i]._name != undefined &&
            entities[i]._name === "楼栋掩膜"
          ) {
            viewer.entities.remove(entities[i]);
            i--;
          }
        }
        // 绘制高亮
        viewer.entities.add({
          id: building.attributes.address,
          name: "楼栋掩膜",
          polygon: {
            hierarchy: Cesium.Cartesian3.fromDegreesArray(points),
            material: new Cesium.Color(1.0, 0.0, 0, 0.5),
            classificationType: Cesium.ClassificationType.S3M_TILE,
          },
        });
      });
      proxy.subList[21] = pubsub.subscribe("hoverBuildingOut", () => {
        // 清除高亮掩膜
        let entities = viewer.entities._entities._array;
        for (let i = 0; i < entities.length; i++) {
          if (
            entities[i]._name != undefined &&
            entities[i]._name === "楼栋掩膜"
          ) {
            viewer.entities.remove(entities[i]);
            i--;
          }
        }
      });
      proxy.subList[22] = pubsub.subscribe("enterprisePointShow", (n, data) => {
        // 视角移动
        scene.camera.flyTo({
          destination: Cesium.Cartesian3.fromDegrees(113.388, 22.8904, 1000),
          orientation: {
            heading: 0,
            pitch: Cesium.Math.toRadians(-90),
            roll: 0,
          },
        });
        setTimeout(() => {
          //缓存数据
          poiList = data;
          // 添加企业标识
          data.forEach((element) => {
            let imgURL = require("../../assets/pic2/icon/" +
              colorList[10].split("#")[1] +
              ".png");
            poiIconLabelAdd(
              Number(element["X"]),
              Number(element["Y"]),
              element["企业名"],
              colorList[10],
              imgURL,
              "企业"
            );
          });
          //开启点击
          clickEnterpriseBillborad();
        }, 500);
      });
      proxy.subList[23] = pubsub.subscribe("quitEnterprise", () => {
        // 视角重置
        initCamera();
        // 删除企业标识
        let entities = viewer.entities._entities._array;
        for (let i = 0; i < entities.length; i++) {
          if (entities[i]._name != undefined && entities[i]._name === "企业") {
            viewer.entities.remove(entities[i]);
            i--;
          }
        }
        deletePOI("企业");
        handlerEnterprise.destroy();
      });
      proxy.subList[24] = pubsub.subscribe("closeIntroduction", () => {
        proxy.villageIntroductionShow = false;
      });
      proxy.subList[25] = pubsub.subscribe("showNet", (n, data) => {
        // 开启网格线
        if (data) {
          //视角移动
          scene.camera.flyTo({
            destination: Cesium.Cartesian3.fromDegrees(113.3875, 22.8938, 1300),
            orientation: {
              heading: 0,
              pitch: Cesium.Math.toRadians(-90),
              roll: 0,
            },
          });
          // 绘制网格线
          net.features.forEach((element) => {
            if (element.attributes.name != "重点示范区") {
              // 绘制新网格线
              var points = new Array(0);
              element.geometry.rings[0].forEach((point) => {
                points.push(point[0]);
                points.push(point[1]);
              });
              viewer.entities.add({
                id: element.attributes.name,
                name: "网格线",
                polygon: {
                  hierarchy: Cesium.Cartesian3.fromDegreesArray(points),
                  material: new Cesium.Color(1.0, 0.0, 0.0, 0.7),
                  outline: true,
                  outlineColor: Cesium.Color.RED,
                  outlineWidth: 5,
                  extrudedHeight: 15,
                  closeBottom: false,
                  closeTop: false,
                  classificationType: Cesium.ClassificationType.S3M_TILE,
                },
              });
              // 添加网格label
              viewer.entities.add({
                id: element.attributes.name + "标识",
                name: "网格线标识",
                position: Cesium.Cartesian3.fromDegrees(
                  Number(element.attributes.x),
                  Number(element.attributes.y) + 0.0002,
                  40
                ),
                label: {
                  //文字标签
                  text: element.attributes.name,
                  scale: 0.1,
                  font: "normal 200px sans-serif",
                  style: Cesium.LabelStyle.FILL,
                  // horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
                  verticalOrigin: Cesium.VerticalOrigin.CENTER,
                  backgroundPadding: new Cesium.Cartesian2(70, 35),
                  showBackground: true,
                  backgroundColor: Cesium.Color.RED,
                },
              });
            }
          });
        }
        // 关闭网格线
        else {
          // 清理标识
          let entities = viewer.entities._entities._array;
          for (let i = 0; i < entities.length; i++) {
            if (
              entities[i]._name != undefined &&
              entities[i]._name.indexOf("网格线") != -1
            ) {
              viewer.entities.remove(entities[i]);
              i--;
            }
          }
          initCamera();
        }
      });
      proxy.subList[26] = pubsub.subscribe("specialPeopleShow", (n, data) => {
        // 开启显示
        if (data.peopleList.length != 0) {
          // 制作标识
          data.peopleList.forEach((element) => {
            let lon = Number(element.location_x);
            let lat = Number(element.location_y);
            viewer.entities.add({
              name: element["网格"] + "特殊人群",
              position: Cesium.Cartesian3.fromDegrees(lon, lat, 25),
              clampToGround: true,
              // 图标
              billboard: {
                image: require("../../assets/pic2/特殊人群.png"),
                width: 30,
                height: 60,
              },
            });
          });
          // 判断是否已有标识
          if (specialPeopleList.length != 0) {
            // 数据存入
            specialPeopleList.push(...data.peopleList);
            return;
          } else {
            // 数据存入
            specialPeopleList.push(...data.peopleList);
            // 视角移动
            scenePosition = null;
            var infoboxContainer = document.getElementById("bubble2");
            // 绑定逐帧计算事件
            postRender(infoboxContainer);
            //标识点击
            handlerSpecialPeople = new Cesium.ScreenSpaceEventHandler(
              scene.canvas
            );
            handlerSpecialPeople.setInputAction(function (movement) {
              let pickedLabel = viewer.scene.pick(movement.position);
              // 点击billborad才更新
              if (
                pickedLabel.id &&
                pickedLabel.id._name.indexOf("特殊人群") != -1
              ) {
                // 获取点击位置笛卡尔坐标
                var position = scene.pickPosition(movement.position);
                scenePosition = position;
                // 从笛卡尔坐标获取经纬度
                var cartographic = Cesium.Cartographic.fromCartesian(position);
                var longitude = Cesium.Math.toDegrees(cartographic.longitude);
                var latitude = Cesium.Math.toDegrees(cartographic.latitude);
                // 距离匹配
                let min = 9999;
                let nearestPOI = {};
                specialPeopleList.forEach((feature) => {
                  let distance = Math.sqrt(
                    Math.pow(Number(feature["location_x"]) - longitude, 2) +
                      Math.pow(Number(feature["location_y"]) - latitude, 2)
                  );
                  if (distance < min) {
                    min = distance;
                    nearestPOI = feature;
                  }
                });
                // console.log(nearestPOI);
                // 填入数据
                proxy.specialPeopleData = [];
                for (let key in nearestPOI) {
                  if (key != "location_x" && key != "location_y")
                    proxy.specialPeopleData.push({
                      key: key,
                      value: nearestPOI[key],
                    });
                }
                proxy.poiShow1 = true;
              }
            }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
          }
        }
        // 关闭显示
        else {
          //清理标识
          let entities = viewer.entities._entities._array;
          for (let i = 0; i < entities.length; i++) {
            if (
              entities[i]._name != undefined &&
              entities[i]._name === data.net + "特殊人群"
            ) {
              viewer.entities.remove(entities[i]);
              i--;
            }
          }
          //清理数组
          let i = 0;
          for (let i = 0; i < specialPeopleList.length; i++) {
            if (specialPeopleList[i]["网格"] === data.net) {
              specialPeopleList.splice(i, 1);
              i--;
            }
          }
          // 若无剩余标识则关闭hanlder
          if (specialPeopleList.length === 0) {
            handlerSpecialPeople.destroy();
          }
        }
      });
      proxy.subList[27] = pubsub.subscribe("modelShowChange", (n, data) => {
        if (data) {
          // 模型恢复显示
          for (var layer of modelLayer) {
            layer.clearModifyRegions();
          }
        } else {
          // 模型隐藏
          let borderPoints = [
            [
              114.398, 23.903, 15, 114.398, 21.887, 15, 112.379, 21.887, 15,
              112.379, 23.903, 15,
            ],
          ];
          for (var layer of modelLayer) {
            layer.setModifyRegions(
              borderPoints,
              Cesium.ModifyRegionMode.CLIP_INSIDE
            );
          }
        }
      });
      proxy.subList[28] = pubsub.subscribe("AddJson", (n, data) => {
        // 绘制
        if (data.isChecked) {
          let jsonData = JSONList[data.label];
          // console.log(jsonData);
          // 拓扑类型
          let type = jsonData.geometryType.split("esriGeometry")[1];
          // 数据载入
          if (type === "Polygon") {
            PolygonShowedList.push({ data: jsonData, name: data.label });
            if (!identifyPolygonFlag) identifyPolygon(true);
          } else {
            PolylineShowedList.push({ data: jsonData, name: data.label });
            if (!identifyPolylineFlag) identifyPolyline(true);
          }
          // 绘制
          jsonData.features.forEach((element) => {
            var points = new Array(0);
            // 面要素
            if (type === "Polygon") {
              element.geometry.rings[0].forEach((point) => {
                points.push(point[0]);
                points.push(point[1]);
              });
              viewer.entities.add({
                id: element.attributes.name,
                name: data.label,
                polygon: {
                  hierarchy: Cesium.Cartesian3.fromDegreesArray(points),
                  material: hexToCesiumColor(data.color, 0.5),
                  outline: true,
                  outlineColor: Cesium.Color.fromCssColorString(data.color),
                  outlineWidth: 2,
                  extrudedHeight: 30,
                },
              });
            }
            // 线要素
            else {
              // console.log(element.geometry.paths);
              element.geometry.paths.forEach((point) => {
                let list = [];
                point.forEach((p) => {
                  list.push(new Cesium.Cartesian3.fromDegrees(p[0], p[1], 2));
                });
                viewer.entities.add({
                  name: data.label,
                  polyline: {
                    positions: list,
                    width: 1.5,
                    material: Cesium.Color.fromCssColorString(data.color),
                  },
                });
              });
            }
          });
        }
        // 清除
        else {
          PolygonShowedList.forEach((element) => {
            if (element.name === data.label)
              PolygonShowedList.splice(PolygonShowedList.indexOf(element), 1);
          });
          if (PolygonShowedList.length === 0 && identifyPolygonFlag === true) {
            identifyPolygon(false);
          }
          PolylineShowedList.forEach((element) => {
            if (element.name === data.label)
              PolylineShowedList.splice(PolylineShowedList.indexOf(element), 1);
          });
          if (
            PolylineShowedList.length === 0 &&
            identifyPolylineFlag === true
          ) {
            identifyPolyline(false);
          }
          let entities = viewer.entities._entities._array;
          for (let i = 0; i < entities.length; i++) {
            if (
              entities[i]._name != undefined &&
              entities[i]._name === data.label
            ) {
              viewer.entities.remove(entities[i]);
              i--;
            } else if (entities[i]._name === "识别标识") {
              viewer.entities.remove(entities[i]);
              i--;
            }
          }
        }
      });
      proxy.subList[29] = pubsub.subscribe("addTransformerFlag", (n, data) => {
        let x = data.x || data.geometry.x;
        let y = data.y || data.geometry.y;
        let mc = data.BYQMC || data.attributes.BYQMC;
        // 添加标识
        poiIconLabelAdd(
          x,
          y,
          mc,
          "#1296db",
          require("../../assets/pic2/icon/1296db.png")
        );
      });
      proxy.subList[30] = pubsub.subscribe("transformerSelected", (n, data) => {
        console.log(data);
        showTransformer(data);
      });
      proxy.subList[31] = pubsub.subscribe("transFormerPOI", (n, data) => {
        console.log(data);
        // poi开关
        if (data.isChecked) {
          addTransformerPOI(data.data);
          clickTransformer();
        } else {
          // 颜色标识回退
          proxy.colorIndex -= 1;
          // 选择器销毁
          handlerTransformer.destroy();
          // 标识清除
          let entities = viewer.entities._entities._array;
          for (let i = 0; i < entities.length; i++) {
            if (
              entities[i]._name != undefined &&
              entities[i]._name.indexOf("大同") != -1
            ) {
              viewer.entities.remove(entities[i]);
              i--;
            }
          }
        }
      });
      proxy.subList[32] = pubsub.subscribe("supplyRange", (n, data) => {
        // 开启供电范围
        if (data) {
          // //视角移动
          // scene.camera.flyTo({
          //   destination: Cesium.Cartesian3.fromDegrees(113.3875, 22.8938, 2000),
          //   orientation: {
          //     heading: 0,
          //     pitch: Cesium.Math.toRadians(-90),
          //     roll: 0,
          //   },
          //   duration: 1.5,
          // });
          // 清理标识
          let entities = viewer.entities._entities._array;
          for (let i = 0; i < entities.length; i++) {
            if (
              entities[i]._name != undefined &&
              entities[i]._name.indexOf("供电范围") != -1
            ) {
              viewer.entities.remove(entities[i]);
              i--;
            }
          }
          // 绘制网格线
          supplyRange.features.forEach((element) => {
            // 绘制新网格线
            var points = new Array(0);
            element.geometry.rings[0].forEach((point) => {
              points.push(point[0], point[1]);
              // points.push(point[0], point[1],50);
            });
            // 绘制wall
            // points.push(...element.geometry.rings[0][1], 50);
            // var rgba = Cesium.Color.fromCssColorString("#d81e06");
            // viewer.entities.add({
            //   id: element.attributes.GDFQMC,
            //   name: "供电范围",
            //   wall: {
            //     positions: Cesium.Cartesian3.fromDegreesArrayHeights(points),
            //     material: new Cesium.ImageMaterialProperty({
            //       transparent: true, //设置透明
            //       image: getColorRamp({
            //         0.0: rgba.withAlpha(1.0).toCssColorString(),
            //         1.0: rgba.withAlpha(0.1).toCssColorString(),
            //       }), //Canvas
            //     }),
            //   },
            // });
            viewer.entities.add({
              id: element.attributes.GDFQMC,
              name: "供电范围",
              polygon: {
                hierarchy: Cesium.Cartesian3.fromDegreesArray(points),
                material: hexToCesiumColor("#1296db", 0.7),
                outline: true,
                outlineColor: hexToCesiumColor("#1296db", 1),
                outlineWidth: 3,
                extrudedHeight: 30,
                closeBottom: false,
                closeTop: false,
                classificationType: Cesium.ClassificationType.S3M_TILE,
              },
            });
            // 添加网格label
            viewer.entities.add({
              id: element.attributes.GDFQMC.split("大同村")[1] + "标识",
              name: "供电范围标识",
              position: Cesium.Cartesian3.fromDegrees(
                Number(element.attributes.x),
                Number(element.attributes.y) + 0.0002,
                40
              ),
              label: {
                //文字标签
                text: element.attributes.GDFQMC + "供电范围",
                scale: 0.1,
                font: "normal 120px sans-serif",
                style: Cesium.LabelStyle.FILL,
                // horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
                verticalOrigin: Cesium.VerticalOrigin.CENTER,
                backgroundPadding: new Cesium.Cartesian2(80, 40),
                showBackground: true,
                backgroundColor: hexToCesiumColor("#1296db", 1),
              },
            });
          });
        }
        // 关闭网格线
        else {
          // 清理标识
          let entities = viewer.entities._entities._array;
          for (let i = 0; i < entities.length; i++) {
            if (
              entities[i]._name != undefined &&
              entities[i]._name.indexOf("供电范围") != -1
            ) {
              viewer.entities.remove(entities[i]);
              i--;
            }
          }
        }
      });
      proxy.subList[33] = pubsub.subscribe("supplyRangeShow", (n, data) => {
        // 清理标识
        let entities = viewer.entities._entities._array;
        for (let i = 0; i < entities.length; i++) {
          if (
            entities[i]._name != undefined &&
            entities[i]._name.indexOf("供电范围") != -1
          ) {
            viewer.entities.remove(entities[i]);
            i--;
          }
        }
        // 绘制新网格线
        let element = data;
        var points = new Array(0);
        element.geometry.rings[0].forEach((point) => {
          points.push(...point);
        });
        viewer.entities.add({
          id: element.attributes.GDFQMC,
          name: "供电范围",
          polygon: {
            hierarchy: Cesium.Cartesian3.fromDegreesArray(points),
            material: hexToCesiumColor("#1296db", 0.7),
            outline: true,
            outlineColor: hexToCesiumColor("#1296db", 1),
            outlineWidth: 3,
            extrudedHeight: 30,
            closeBottom: false,
            closeTop: false,
            classificationType: Cesium.ClassificationType.S3M_TILE,
          },
        });
        // 添加网格label
        // viewer.entities.add({
        //   id: element.attributes.GDFQMC + "标识",
        //   name: "供电范围标识",
        //   position: Cesium.Cartesian3.fromDegrees(
        //     Number(element.attributes.x),
        //     Number(element.attributes.y) + 0.0002,
        //     40
        //   ),
        //   label: {
        //     //文字标签
        //     text: element.attributes.GDFQMC,
        //     scale: 0.1,
        //     font: "normal 150px sans-serif",
        //     style: Cesium.LabelStyle.FILL,
        //     // horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
        //     verticalOrigin: Cesium.VerticalOrigin.CENTER,
        //     backgroundPadding: new Cesium.Cartesian2(70, 35),
        //     showBackground: true,
        //     backgroundColor: hexToCesiumColor("#1296db", 1),
        //   },
        // });
      });
      proxy.subList[34] = pubsub.subscribe("housePolygonShow", (n, data) => {
        if (data) {
          buildingJSON.features.forEach((element) => {
            // console.log(element);
            let points = [];
            element.geometry.rings[0].forEach((point) => {
              points.push(point[0]);
              points.push(point[1]);
            });
            viewer.entities.add({
              id: element.attributes["x"] + "," + element.attributes["y"],
              name: "全区房屋面",
              polygon: {
                hierarchy: Cesium.Cartesian3.fromDegreesArray(points),
                material: hexToCesiumColor("#f89407", 0.8),
              },
            });
          });
        } else {
          // 清除
          let entities = viewer.entities._entities._array;
          for (let i = 0; i < entities.length; i++) {
            if (entities[i]._name === "全区房屋面") {
              viewer.entities.remove(entities[i]);
              i--;
            }
          }
        }
      });
      proxy.subList[35] = pubsub.subscribe("recommendPolygon", (n, data) => {
        if (data) {
          recommendJSON.features.forEach((element) => {
            // 添加示意面与示意箱
            let points = [];
            element.geometry.rings[0].forEach((point) => {
              points.push(point[0]);
              points.push(point[1]);
            });
            viewer.entities.add({
              id: element.attributes["名称"] + "示意",
              name: "新增推荐面",
              polygon: {
                hierarchy: Cesium.Cartesian3.fromDegreesArray(points),
                material: hexToCesiumColor("#d4237a", 0.5),
                classificationType: Cesium.ClassificationType.S3M_TILE,
              },
            });
            viewer.entities.add({
              id: element.attributes["名称"] + "示意边界",
              name: "新增推荐面",
              polygon: {
                hierarchy: Cesium.Cartesian3.fromDegreesArray(points),
                material: hexToCesiumColor("#d4237a", 0.5),
                outline: true,
                outlineColor: Cesium.Color.fromCssColorString("#d4237a"),
                outlineWidth: 2,
                extrudedHeight: 15,
              },
            });
            // 添加示意标识
            let imgURL = require("../../assets/pic2/icon/d4237a.png");
            poiIconLabelAdd(
              Number(element.attributes["x"]),
              Number(element.attributes["y"]),
              element.attributes["名称"],
              "#d4237a",
              imgURL
            );
          });
          pubsub.publish("handlerRecommend", true);
        } else {
          pubsub.publish("handlerRecommend", false);
          // 清除
          deleteLayer("新增");
        }
      });
      proxy.subList[36] = pubsub.subscribe("mapSetView", (n, data) => {
        scene.camera.flyTo({
          destination: Cesium.Cartesian3.fromDegrees(data.x, data.y, 200),
          orientation: {
            heading: 0,
            pitch: Cesium.Math.toRadians(-90),
            roll: 0,
          },
          duration: 1.5,
        });
      });
      proxy.subList[37] = pubsub.subscribe("handlerRecommend", (n, data) => {
        if (data) {
          handlerRecommend = new Cesium.ScreenSpaceEventHandler(scene.canvas);
          handlerRecommend.setInputAction(function (movement) {
            let pickedLabel = viewer.scene.pick(movement.position);
            let name = "";
            if (!pickedLabel) {
              return;
            } else {
              name = pickedLabel.id._name;
            }
            pickedLabel = pickedLabel.id;
            console.log(name);
            // 点击billborad才更新
            if (pickedLabel) {
              // 跳转至详细信息
              recommendJSON.features.forEach((transformer) => {
                if (transformer.attributes["名称"] === name) {
                  // 信息传输
                  // pubsub.publish("recommendData", transformer.attributes);
                  //传入左侧展示栏
                  pubsub.publish("identifyDataShow", transformer.attributes);
                }
              });
            }
          }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
        } else {
          handlerRecommend.destroy();
          // 查询结果退出
          pubsub.publish("AddJson", { isCheeck: false });
        }
      });
      proxy.subList[38] = pubsub.subscribe("houseLoadSearch", (n, data) => {
        houseLoadSearch(data.isOn);
      });
      proxy.subList[39] = pubsub.subscribe("recLayerControll", (n, data) => {
        console.log(data);
        // 开启显示
        if (data.flag) {
          if (data.index === 4) {
            drawRecommendResult(data.name);
          } else {
            drawReferenceLayer(data.name, data.index);
          }
        }
        // 关闭显示
        else {
          if (layerList[data.index]) {
            deleteLayer(layerList[data.index].name);
          } else {
            deleteLayer("推荐");
            handlerRecommend.destroy();
          }
        }
      });
      proxy.subList[40] = pubsub.subscribe("landUse", (n, data) => {
        if (data) {
          // 添加图层
          serverLayer = viewer.imageryLayers.addImageryProvider(
            new Cesium.ArcGisMapServerImageryProvider({
              url: "http://localhost:6080/arcgis/rest/services/大同村/土地利用现状/MapServer",
            })
          );
          // 开启查询
          handlerLanduse = new Cesium.ScreenSpaceEventHandler(scene.canvas);
          handlerLanduse.setInputAction(function (movement) {
            var position = scene.pickPosition(movement.position);
            if (!position) {
              position = Cesium.Cartesian3.fromDegrees(0, 0, 0);
            }
            scenePosition = position; // 气泡相关

            // 执行arcgisserver点选查询
            cesiumApi.serverIdentify(
              movement.position,
              "http://localhost:6080/arcgis/rest/services/大同村/土地利用现状/",
              (data) => {
                // 属性信息传输
                // pubsub.publish("cesiumApi.serverIdentify", data);
                proxy.tableData = [];
                console.log(data);
                let keyList = [
                  {
                    key: "DLMC",
                    value: "地类名称",
                  },
                  {
                    key: "Shape_Area",
                    value: "土地面积（㎡）",
                  },
                  {
                    key: "QSDWMC",
                    value: "权属单位名称",
                  },
                ];
                for (const key in data) {
                  keyList.forEach((element) => {
                    if (key === element.key) {
                      proxy.tableData.push({
                        key: element.value,
                        value: data[key],
                      });
                    }
                  });
                }
                proxy.poiShow = true;
              },
              (polygon) => {
                // 清除旧标识掩膜
                let entities = viewer.entities._entities._array;
                for (let i = 0; i < entities.length; i++) {
                  if (
                    entities[i]._name != undefined &&
                    entities[i]._name === "土地利用现状高亮面"
                  ) {
                    viewer.entities.remove(entities[i]);
                    i--;
                  }
                }
                // 绘制新多边形高亮标识
                viewer.entities.add({
                  name: "土地利用现状高亮面",
                  polygon: {
                    hierarchy: Cesium.Cartesian3.fromDegreesArray(polygon),
                    material: new Cesium.Color(1.0, 0.0, 0.0, 0.7),
                    outline: true,
                    outlineColor: Cesium.Color.RED,
                    outlineWidth: 2,
                    extrudedHeight: 1,
                    closeBottom: false,
                    closeTop: false,
                    classificationType: Cesium.ClassificationType.S3M_TILE,
                  },
                });
              }
            );
          }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
          // 信息提示
          ElMessage({
            message: "土地利用现状图层加载成功",
            type: "success",
          });
        } else {
          // 关闭图层显示
          viewer.imageryLayers.remove(serverLayer);
          // 清除旧标识掩膜
          let entities = viewer.entities._entities._array;
          for (let i = 0; i < entities.length; i++) {
            if (
              entities[i]._name != undefined &&
              entities[i]._name === "土地利用现状高亮面"
            ) {
              viewer.entities.remove(entities[i]);
              i--;
            }
          }
          // 关闭搜索
          handlerLanduse.destroy();
        }
      });
    }

    // 地图相关操作
    function onload(Cesium) {
      // 初始化地图
      initMap(Cesium);
      Cesium.when(
        promise,
        function (layers) {
          modelLayer = layers;
          // 相机定位
          initCamera();
        },
        function (e) {
          if (widget._showRenderLoopErrors) {
            var title = "加载SCP失败，请检查网络连接状态或者url地址是否正确？";
            widget.showErrorPanel(title, undefined, e);
          }
        }
      );
    }

    // 初始化地图
    function initMap(Cesium) {
      // 初始化viewer部件
      window.viewer = new Cesium.Viewer("cesiumContainer", {
        infoBox: false,
        selectionIndicator: false,
        animation: false, //左下角的动画仪表盘
        baseLayerPicker: false, //右上角的图层选择按钮
        geocoder: false, //搜索框
        homeButton: false, //home按钮
        sceneModePicker: false, //模式切换按钮
        timeline: false, //底部的时间轴
        navigationHelpButton: false, //右上角的帮助按钮，
        fullscreenButton: false, //右下角的全屏按钮
        infoBox: false, //小弹窗
        selectionIndicator: false,
        zoomIndicatorContainer: false,
        navigation: false, //指南针
      });
      window.scene = viewer.scene;
      scene = viewer.scene;
      viewer.scene.globe.depthTestAgainstTerrain = true;
      scene.debugShowFramesPerSecond = false;
      viewer.scene.fxaa = true;
      viewer.scene.postProcessStages.fxaa.enabled = true;

      scenePosition = null;
      var infoboxContainer = document.getElementById("bubble1");
      // 绑定逐帧计算事件
      postRender(infoboxContainer);

      if (Cesium.FeatureDetection.supportsImageRenderingPixelated()) {
        //判断是否支持图像渲染像素化处理
        viewer.resolutionScale = window.devicePixelRatio;
      }
      //添加底图
      viewer.imageryLayers.addImageryProvider(
        new Cesium.ArcGisMapServerImageryProvider({
          // url: url.yxURL136,
          url: url.yxURL,
        })
      );

      //添加模型
      promise = viewer.scene.open(url.mxURL);
      // recommend("大同村13号");
    }

    // 相机定位
    function initCamera() {
      // 相机定位
      scene.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(113.383, 22.891, 300),
        // destination: Cesium.Cartesian3.fromDegrees(113.385, 22.884, 300),
        orientation: {
          heading: 0.7,
          pitch: -0.5,
          roll: 0,
        },
      });
    }

    // 绘制参考面
    function drawReferenceLayer(name, i) {
      console.log(name, i);
      // 参考面筛选
      // for (let i = 0; i < layerList.length; i++) {
      //   layerList[i].features.push();
      // }
      console.log(recommendLayer);
      layerList[i].features = recommendLayer.features.filter((element) => {
        return (
          Number(element.attributes.type) === i &&
          element.attributes.GDFQMC.split("大同村")[1].split("#")[0] === name
        );
      });
      console.log(layerList);
      // 绘制各个参考图层
      layerList.forEach((element) => {
        element.features.forEach((layer) => {
          layer.geometry.rings.forEach((ring) => {
            let points = [];
            ring.forEach((point) => {
              points.push(...point);
            });
            // 相斥图层
            if (element.color) {
              element.layer = viewer.entities.add({
                name: element.name,
                polygon: {
                  hierarchy: Cesium.Cartesian3.fromDegreesArray(points),
                  material: hexToCesiumColor(element.color, 0.7),
                  outline: true,
                  outlineColor: Cesium.Color.fromCssColorString(element.color),
                  outlineWidth: 2,
                },
              });
            }
            // 集体用地
            else {
              element.layer = viewer.entities.add({
                name: element.name,
                polygon: {
                  hierarchy: Cesium.Cartesian3.fromDegreesArray(points),
                  material: hexToCesiumColor("#f89407", 0.7),
                  outline: true,
                  outlineColor: Cesium.Color.fromCssColorString("#f89407"),
                  outlineWidth: 4,
                  extrudedHeight: 15,
                  closeBottom: false,
                  closeTop: false,
                },
              });
            }
          });
        });
      });
    }

    // 绘制推荐结果
    function drawRecommendResult(name) {
      // 绘制推荐面
      recommendResult.features.forEach((element) => {
        if (
          element.attributes.GDFQMC.split("大同村")[1].split("#")[0] === name
        ) {
          // 坐标整理
          var points = new Array(0);
          element.geometry.rings[0].forEach((point) => {
            points.push(...point);
          });
          // 绘制图层面
          let color = "#d81e06";
          let opacity = 0.4;
          resultLayer.push(
            viewer.entities.add({
              name: "推荐地块",
              polygon: {
                hierarchy: Cesium.Cartesian3.fromDegreesArray(points),
                material: hexToCesiumColor(color, opacity),
                outline: true,
                outlineColor: Cesium.Color.fromCssColorString(color),
                outlineWidth: 3,
                extrudedHeight: 10,
                closeBottom: false,
              },
            }),
            viewer.entities.add({
              name: "推荐地块",
              polygon: {
                hierarchy: Cesium.Cartesian3.fromDegreesArray(points),
                material: hexToCesiumColor(color, opacity),
              },
            })
          );
          // 绘制标识
          let imgURL = require("../../assets/pic2/icon/" +
            color.split("#")[1] +
            ".png");
          console.log(element.attributes);
          poiIconLabelAdd(
            Number(element.attributes.x),
            Number(element.attributes.y),
            element.attributes.name,
            color,
            imgURL
          );
        }
      });
      // 开启查询
      handlerRecommend = new Cesium.ScreenSpaceEventHandler(scene.canvas);
      handlerRecommend.setInputAction(function (movement) {
        let pickedLabel = viewer.scene.pick(movement.position);
        let name = "";
        if (!pickedLabel) {
          return;
        } else {
          name = pickedLabel.id._name;
        }
        pickedLabel = pickedLabel.id;
        console.log(name);
        // 点击billborad才更新
        if (pickedLabel) {
          // 跳转至详细信息
          recommendResult.features.forEach((transformer) => {
            if (transformer.attributes["name"] === name) {
              // 信息传输
              pubsub.publish("recommendLayerData", transformer.attributes);
            }
          });
        }
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    }

    // 删除指定名称的图层
    function deleteLayer(name) {
      let entities = viewer.entities._entities._array;
      for (let i = 0; i < entities.length; i++) {
        if (
          entities[i]._name != undefined &&
          entities[i]._name.indexOf(name) != -1
        ) {
          viewer.entities.remove(entities[i]);
          i--;
        }
      }
    }

    // 材质绘制代码
    function getColorRamp(val) {
      if (val == null) {
        val = {
          0.0: "blue",
          0.1: "cyan",
          0.37: "lime",
          0.54: "yellow",
          1: "red",
        };
      }
      var ramp = document.createElement("canvas");
      ramp.width = 1;
      ramp.height = 100;
      var ctx = ramp.getContext("2d");
      var grd = ctx.createLinearGradient(0, 0, 0, 100);
      for (var key in val) {
        grd.addColorStop(1 - Number(key), val[key]);
      }
      ctx.fillStyle = grd;
      ctx.fillRect(0, 0, 1, 100);
      return ramp;
    }

    //绘制裁剪面
    function drawToCut() {
      let points = [];
      router.push({
        path: "polygonCut",
      });
      // 视图移动
      scene.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(113.5439, 22.80495, 500),
        orientation: {
          heading: 0.03,
          pitch: -1.55,
          roll: 0,
        },
      });
      // 启动绘制面
      handlerPolygon = new Cesium.DrawHandler(
        viewer,
        Cesium.DrawMode.Polygon,
        0
      );
      // 激活绘制
      handlerPolygon.activate();
      handlerPolygon.drawEvt.addEventListener(function (result) {
        handlerPolygon.polygon.show = false;
        handlerPolygon.polyline.show = false;
        //   收集绘制的点
        positions = [];
        let centerX = 0;
        let centerY = 0;
        for (var pt of result.object.positions) {
          var cartographic = Cesium.Cartographic.fromCartesian(pt);
          var longitude = Cesium.Math.toDegrees(cartographic.longitude);
          var latitude = Cesium.Math.toDegrees(cartographic.latitude);
          if (centerX === 0) {
            centerX = longitude;
            centerY = latitude;
          } else {
            centerX = (longitude + centerX) / 2;
            centerY = (latitude + centerY) / 2;
          }
          positions.push(longitude, latitude, 15);
          points.push(longitude, latitude);
        }
        // console.log("绘制面的中心坐标为：", centerX, centerY);
        console.log(positions);
        //   绘制绘成的面
        regions = [];
        regions.push(positions);
        //   按照绘成的面截取模型
        for (var layer of modelLayer) {
          layer.setModifyRegions(regions, Cesium.ModifyRegionMode.CLIP_OUTSIDE);
        }
        //   视图移动
        scene.camera.flyTo({
          destination: Cesium.Cartesian3.fromDegrees(
            centerX - 0.000165,
            centerY - 0.00075,
            50
          ),
          orientation: {
            heading: 4.4231285301066237e-13,
            pitch: -0.4,
            roll: 0,
          },
        });
        proxy.tipShow = false;
        // 跳转
        pubsub.publish("drawPolygon", regions);
        // 绘制遮罩
        drawHierarchy(points);
      });
    }

    //绘制遮罩函数
    function drawHierarchy(points) {
      console.log(points);
      // 内部线
      var maskspoint = Cesium.Cartesian3.fromDegreesArray(points);
      // 外部线
      let p = Cesium.Cartesian3.fromDegreesArray([
        123.53531187734892, 12.811852230539827, 123.53489791505173,
        32.799416992097346, 103.55847696517246, 32.79809874434965,
        103.55629545308248, 12.811776391024242,
      ]);
      viewer.entities.add({
        name: "线1",
        polygon: {
          hierarchy: {
            positions: p, //外部区域
            holes: [
              {
                positions: maskspoint, //挖空区域
              },
            ],
          },
          material: Cesium.Color.BLACK.withAlpha(0.7), //外部颜色
        },
      });
    }

    // 网格线截取
    function cutByNet(netID) {
      // 关闭除此之外的网格线
      viewer.entities.removeAll();
      net.features.forEach((element) => {
        if (element.attributes.name === netID) {
          var points = new Array(0);
          element.geometry.rings[0].forEach((point) => {
            points.push(point[0]);
            points.push(point[1]);
          });
          viewer.entities.add({
            id: netID,
            name: "网格线",
            polygon: {
              hierarchy: Cesium.Cartesian3.fromDegreesArray(points),
              material: Cesium.Color.RED.withAlpha(0),
              outline: true,
              outlineColor: Cesium.Color.RED,
              outlineWidth: 5,
              clampToS3M: true,
            },
          });
        }
      });
      // 根据网格线裁剪
      net.features.forEach((element) => {
        var points = new Array(0);
        if (element.attributes.name === netID) {
          element.geometry.rings[0].forEach((point) => {
            points.push(point[0]);
            points.push(point[1]);
            points.push(15);
          });
          points.push(
            element.geometry.rings[0][0][0],
            element.geometry.rings[0][0][1],
            15
          );
          //裁剪模型
          let polygon = [];
          polygon.push(points);
          //   按照绘成的面截取模型
          for (var layer of modelLayer) {
            layer.setModifyRegions(
              polygon,
              Cesium.ModifyRegionMode.CLIP_OUTSIDE
            );
          }
          // 绘制遮罩
          let maskspoint = [];
          element.geometry.rings[0].forEach((element) => {
            maskspoint.push(element[0]);
            maskspoint.push(element[1]);
          });
          drawHierarchy(maskspoint);
        }
      });
    }

    // 开启单体化楼栋点击
    function clickBuildingOn() {
      maskON = true;
      // 视图切换
      scene.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(113.389, 22.8955, 700),
        orientation: {
          heading: 0.1,
          pitch: -1.6,
          roll: 0,
        },
      });
      // 开启标识
      buildingclicking = true;
      // 创建事件处理器
      handler = new Cesium.ScreenSpaceEventHandler(scene.canvas);
      handler.setInputAction(function (e) {
        // 获取点击位置笛卡尔坐标
        var position = scene.pickPosition(e.position);
        // 从笛卡尔坐标获取经纬度
        var cartographic = Cesium.Cartographic.fromCartesian(position);
        var longitude = Cesium.Math.toDegrees(cartographic.longitude);
        var latitude = Cesium.Math.toDegrees(cartographic.latitude);
        console.log(longitude, latitude);
        // 删除旧标识
        cesiumApi.deleteFeature("房屋识别结果");
        // 添加标识
        let imgURL = require("../../assets/pic2/icon/1296db.png");
        poiIconLabelAdd(longitude, latitude, "房屋识别结果", "#1296db", imgURL);
        // 发送至后端
        axios({
          method: "get",
          url: url.basicURL + "/clickBuilding",
          params: { lon: longitude, lat: latitude },
        }).then((res) => {
          let searchResult = [];
          // 删除英文字段
          for (const key in res.data[0]) {
            searchResult.push({
              key: key,
              value: res.data[0][key],
            });
          }
          // 传输至显示栏
          pubsub.publish("dataDisplay", {
            show: true,
            tableData: searchResult,
          });
          // console.log(searchResult);
        });
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    }

    // 关闭单体化楼栋点击
    function clickBuildingOff() {
      maskON = false;
      // 去除当前裁剪操作
      for (var layer of modelLayer) {
        layer.clearModifyRegions();
      }
      buildingclicking = false;
      handler.destroy();
      ElMessage({
        message: "楼栋点选关闭",
        type: "success",
      });
      // 删除旧标识
      cesiumApi.deleteFeature("房屋识别结果");
      store.commit("changeClickToBuilding", false);
      pubsub.publish("firstPageShowChange", true);
      pubsub.publish("dataDisplay", { show: false });
    }

    // 按距离匹配楼栋
    function matchByDistance(longitude, latitude, json = buildingPosition) {
      let minDistance = 9999;
      let nearestBuilding;
      json.features.forEach((element) => {
        let x = element.attributes["x"];
        let y = element.attributes["y"];
        let distance = Math.sqrt(
          Math.pow(x - longitude, 2) + Math.pow(y - latitude, 2)
        );
        if (distance < minDistance) {
          minDistance = distance;
          nearestBuilding = element;
        }
      });
      return nearestBuilding;
    }

    // 显示变压器
    function showTransformer(building) {
      // 匹配变压器
      transformerJSON.features.forEach((e) => {
        if (e.attributes["BYQMC"] === building.attributes["BYQMC"]) {
          pubsub.publish("GFshowChange", true);
          pubsub.publish("transformerData", e);
          pubsub.publish("addTransformerFlag", e);
          supplyLineJSON.features.forEach((element) => {
            let line = [];
            element.geometry.paths[0].forEach((points) => {
              line.push(
                Cesium.Cartesian3.fromDegrees(points[0], points[1], 20)
              );
            });
            console.log(line);
            // 创建光点的位置属性
            var positionProperty = new Cesium.SampledPositionProperty();
            for (var i = 0; i < line.length; i += 2) {
              var time = Cesium.JulianDate.fromDate(
                new Date(2023, 0, i / 2 + 1)
              );
              positionProperty.addSample(time, line);
            }

            // 创建光点实体
            let glowLineEntity = viewer.entities.add({
              position: positionProperty,
              point: {
                pixelSize: 1000,
                color: Cesium.Color.YELLOW,
              },
            });
            // 飞行到线的位置
            viewer.flyTo(glowLineEntity);
            // 绘制12号台区供电线路
            // viewer.entities.add({
            //   name: "供电线路",
            //   polyline: {
            //     positions: line,
            //     width: 5,
            //     material: new Cesium.PolylineGlowMaterialProperty({
            //       glowPower: 0.5,
            //       color: Cesium.Color.fromCssColorString("#00FFFF"),
            //     }),
            //   },
            // });
          });
        }
      });
    }

    //显示单体楼栋
    function showBuilding(building) {
      if (isBuildingSelected) {
        // console.log("isBuildingSelected");
        console.log(building);
        pubsub.publish("containerShowChange", true);
        // 楼栋处理
        pubsub.publish("buildingSelect", building);
        router.push({
          path: "/buildingSelected",
        });
      }
      let centerX = building.attributes["x"] || building.geometry.x;
      let centerY = building.attributes["y"] || building.geometry.y;
      //  视图移动
      scene.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(
          // centerX - 0.0007,
          // centerY - 0.0005,
          centerX,
          centerY,
          700
        ),
        // orientation: {
        //   heading: 0.9,
        //   pitch: -0.6,
        //   roll: 0,
        // },
        orientation: {
          heading: 0,
          pitch: Cesium.Math.toRadians(-90),
          roll: 0,
        },
        duration: 2,
      });
      // 高亮掩膜
      // console.log(maskON);
      if (maskON) {
        //扩展角点;
        let expand = 0.00003;
        let points = [];
        building.geometry.rings[0].forEach((element) => {
          let x = element[0];
          let y = element[1];
          centerX < x ? (x = x + expand) : (x = x - expand);
          centerY < y ? (y = y + expand) : (y = y - expand);
          points.push(x, y);
        });
        // 清除高亮掩膜
        let entities = viewer.entities._entities._array;
        for (let i = 0; i < entities.length; i++) {
          if (
            entities[i]._name != undefined &&
            entities[i]._name === "楼栋掩膜"
          ) {
            viewer.entities.remove(entities[i]);
            i--;
          }
        }
        //绘制高亮;
        viewer.entities.add({
          id: building.attributes.address,
          name: "楼栋掩膜",
          polygon: {
            hierarchy: Cesium.Cartesian3.fromDegreesArray(points),
            material: new Cesium.Color(1.0, 0.0, 0, 0.5),
            classificationType: Cesium.ClassificationType.S3M_TILE,
          },
        });
      }
    }

    //添加多类二POI
    function addPOIList(features) {
      poiList = features;
      // 地物类型整合
      let lbList = [features[0]["LB"]];
      let lb = features[0]["LB"];
      features.forEach((feature) => {
        if (feature["LB"] != lb) {
          let isNew = true;
          lbList.forEach((element) => {
            if (element === feature["LB"]) isNew = false;
          });
          if (isNew) {
            lbList.push(feature["LB"]);
            lb = feature["LB"];
          }
        }
      });
      // console.log(lbList);
      // 按地物类别绘制标识
      for (let i = 0; i < lbList.length; i++) {
        features.forEach((feature) => {
          if (feature["LB"] === lbList[i]) {
            let imgURL = require("../../assets/pic2/icon/" +
              colorList[i].split("#")[1] +
              ".png");
            poiIconLabelAdd(
              Number(feature["84Lng"]),
              Number(feature["84Lat"]),
              feature["LB"],
              colorList[i],
              imgURL
            );
          }
        });
      }
    }

    //添加单类POI
    function addPOI(features) {
      console.log(features);
      poiList = features;
      features.forEach((feature) => {
        let imgURL = require("../../assets/pic2/icon/" +
          colorList[proxy.colorIndex].split("#")[1] +
          ".png");
        poiIconLabelAdd(
          Number(feature["X"]),
          Number(feature["Y"]),
          feature["类型"],
          colorList[proxy.colorIndex],
          imgURL
        );
      });
      proxy.colorIndex += 1;
    }

    //添加单个POI
    function poiIconLabelAdd(
      lon,
      lat,
      name,
      color,
      url,
      poiName = name,
      height = 50
    ) {
      console.log(arguments);
      viewer.entities.add({
        // id: "设施" + name + lon + lat,
        name: poiName,
        position: Cesium.Cartesian3.fromDegrees(lon, lat, height),
        // 图标
        billboard: {
          image: url,
          width: 30,
          height: 30,
          rotation: 20,
        },
        label: {
          //文字标签
          text: name,
          scale: 0.1,
          font: "normal 150px sans-serif",
          style: Cesium.LabelStyle.FILL,
          // 对齐方式(水平和竖直)
          horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
          verticalOrigin: Cesium.VerticalOrigin.CENTER,
          backgroundPadding: new Cesium.Cartesian2(100, height),
          pixelOffset: new Cesium.Cartesian2(20, -2),
          showBackground: true,
          backgroundColor: new Cesium.Color.fromCssColorString(color),
        },
      });

      // 先画线后画点，防止线压盖点
      let linePositions = [];
      linePositions.push(new Cesium.Cartesian3.fromDegrees(lon, lat, 0));
      linePositions.push(new Cesium.Cartesian3.fromDegrees(lon, lat, height));
      console.log(linePositions);
      viewer.entities.add({
        name: poiName + "1",
        polyline: {
          positions: linePositions,
          width: 1.5,
          material: new Cesium.Color.fromBytes(255, 255, 255),
        },
      });

      // 画点
      viewer.entities.add({
        name: poiName + "2",
        // 给初始点位设置一定的离地高度，否者会被压盖
        position: Cesium.Cartesian3.fromDegrees(lon, lat, 7),
        point: {
          color: new Cesium.Color.fromBytes(255, 255, 255),
          pixelSize: 15,
        },
      });
    }

    // 删除二维标记
    function deletePOI(name) {
      let entities = viewer.entities._entities._array;
      for (let i = 0; i < entities.length; i++) {
        if (
          entities[i]._name != undefined &&
          entities[i]._name.indexOf(name) != -1
        ) {
          viewer.entities.remove(entities[i]);
          i--;
        }
      }
      let recursion = false;
      viewer.entities._entities._array.some((e) => {
        if (e._name != undefined && e._name.indexOf(name) != -1) {
          recursion = true;
          return true;
        }
      });
      if (recursion) deletePOI(name);
    }

    // billborad点击生成气泡
    function clickMap() {
      scenePosition = null;
      var infoboxContainer = document.getElementById("bubble1");
      // 绑定逐帧计算事件
      postRender(infoboxContainer);
      // 绑定billborad点击事件
      clickBillborad();
    }

    // 逐帧计算
    function postRender(infoboxContainer) {
      viewer.scene.postRender.addEventListener(function () {
        // 每一帧都去计算气泡的正确位置
        if (scenePosition) {
          var canvasHeight = scene.canvas.height;
          var windowPosition = new Cesium.Cartesian2();
          Cesium.SceneTransforms.wgs84ToWindowCoordinates(
            scene,
            scenePosition,
            windowPosition
          );
          infoboxContainer.style.bottom =
            canvasHeight - windowPosition.y - 50 + "px";
          infoboxContainer.style.left = windowPosition.x - 40 + "px";
          infoboxContainer.style.visibility = "visible";
        }
      });
    }

    // 点击billborad
    function clickBillborad() {
      if (!clickReady) {
        clickReady = true;
        handlerBillborad = new Cesium.ScreenSpaceEventHandler(scene.canvas);
        handlerBillborad.setInputAction(function (movement) {
          let pickedLabel = viewer.scene.pick(movement.position);
          let name = "";
          if (!pickedLabel) {
            return;
          } else {
            name = pickedLabel.id._name;
          }
          let label = "";
          if (name != undefined && name.indexOf("单个设施选中") != -1) {
            label = pickedLabel.id._name.split("单个设施选中")[1];
          } else {
            label = pickedLabel.id._name;
          }
          console.log(pickedLabel);
          pickedLabel = pickedLabel.id;
          // 点击billborad才更新
          if (pickedLabel && !buildingclicking) {
            // 获取点击位置笛卡尔坐标
            var position = scene.pickPosition(movement.position);
            if (!position) {
              position = Cesium.Cartesian3.fromDegrees(0, 0, 0);
            }
            scenePosition = position; // 气泡相关
            // 从笛卡尔坐标获取经纬度
            var cartographic = Cesium.Cartographic.fromCartesian(position);
            var longitude = Cesium.Math.toDegrees(cartographic.longitude);
            var latitude = Cesium.Math.toDegrees(cartographic.latitude);
            // 距离匹配
            let min = 9999;
            let nearestPOI = {};
            // console.log(label);
            poiList.forEach((feature) => {
              if (feature["类型"] === label) {
                let distance = Math.sqrt(
                  Math.pow(Number(feature["X"]) - longitude, 2) +
                    Math.pow(Number(feature["Y"]) - latitude, 2)
                );
                if (distance < min) {
                  min = distance;
                  nearestPOI = feature;
                }
              }
            });
            // console.log(nearestPOI);
            // 填入数据
            proxy.tableData = [];
            // proxy.bubbleTitle = nearestPOI["名称"];
            let keyList = ["名称", "地址", "网格", "管理员名称", "管理员电话"];
            let i = 0;
            for (let key in nearestPOI) {
              keyList.forEach((key1) => {
                if (key1 === key) {
                  proxy.tableData.push({
                    key: key,
                    value: nearestPOI[key],
                  });
                }
              });
            }
            proxy.poiShow = true;
          }
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
      }
    }

    //popup关闭
    function close() {
      proxy.poiShow = false;
    }

    //视角旋转
    function rotateCamera(lng, lat, distance) {
      var position = Cesium.Cartesian3.fromDegrees(lng, lat, 0.0);
      // 相机看点的角度，如果大于0那么则是从地底往上看，所以要为负值，这里取-30度
      var pitch = Cesium.Math.toRadians(-30);
      // 给定飞行一周所需时间，比如30s, 那么每秒转动度数
      var angle = 360 / 60;
      // 给定相机距离点多少距离飞行
      // var distance = 500;
      var startTime = Cesium.JulianDate.fromDate(new Date());
      var stopTime = Cesium.JulianDate.addSeconds(
        startTime,
        60,
        new Cesium.JulianDate()
      );
      viewer.clock.startTime = startTime.clone(); // 开始时间
      viewer.clock.stopTime = stopTime.clone(); // 结速时间
      viewer.clock.currentTime = startTime.clone(); // 当前时间
      viewer.clock.clockRange = Cesium.ClockRange.CLAMPED; // 行为方式
      viewer.clock.clockStep = Cesium.ClockStep.SYSTEM_CLOCK; // 时钟设置为当前系统时间; 忽略所有其他设置。
      // 相机的当前heading
      var initialHeading = viewer.camera.heading;
      var Exection = function TimeExecution() {
        // 当前已经过去的时间，单位s
        var delTime = Cesium.JulianDate.secondsDifference(
          viewer.clock.currentTime,
          viewer.clock.startTime
        );
        // 根据过去的时间，计算偏航角的变化
        var heading = Cesium.Math.toRadians(delTime * angle) + initialHeading;

        viewer.camera.lookAt(
          position,
          new Cesium.HeadingPitchRange(heading, pitch, distance)
        );

        if (
          Cesium.JulianDate.compare(
            viewer.clock.currentTime,
            viewer.clock.stopTime
          ) >= 0
        ) {
          // location.reload();
          window.viewer.trackEntity = undefined;
          window.viewer.camera.lookAtTransform(Cesium.Matrix4.IDENTITY);
          viewer.clock.onTick.removeEventListener(Exection);
        }
      };
      return Exection;
    }

    //点与多边形求交
    function intersectPolygon(position, polygon) {
      // console.log(position, polygon);
      if (polygon[0][0] > 100000) {
        polygon.forEach((ring) => {
          ring.reverse();
        });
      }
      // 四至截取
      let squareIntersect = MaxAndMin(position, polygon);
      // 射线求交
      if (squareIntersect) return RayIntersection([position], polygon);
    }

    // 四至截取
    function MaxAndMin(position, rangePoints) {
      //  读取四至
      let lngMax = 0;
      let lngMin = 9999999999999999;
      let latMax = 0;
      let latMin = 999999999999999;
      rangePoints.forEach((point) => {
        let lng = point[0];
        let lat = point[1];
        if (lng > lngMax) lngMax = lng;
        if (lng < lngMin) lngMin = lng;
        if (lat > latMax) latMax = lat;
        if (lat < latMin) latMin = lat;
      });
      //四至求交
      let isIntersected = false;
      // console.log(position, lngMax, lngMin, latMax, latMin);
      if (
        position.x < lngMax &&
        position.x > lngMin &&
        position.y < latMax &&
        position.y > latMin
      ) {
        isIntersected = true;
      }
      return isIntersected;
    }

    // 射线求交
    function RayIntersection(enterpriseList, rangePoints) {
      let borderIntersect = false;
      // 遍历四至截取后的企业点,记录水平交点数量
      enterpriseList.forEach((element) => {
        let count = 0;
        let points = [];
        for (let i = 0; i < rangePoints.length - 1; i++) {
          //  确认当前边界点与前一边界点y值的高低
          let latMax, latMin;
          if (rangePoints[i][0] > rangePoints[i + 1][0]) {
            latMax = rangePoints[i][0];
            latMin = rangePoints[i + 1][0];
          } else {
            latMax = rangePoints[i + 1][0];
            latMin = rangePoints[i][0];
          }
          //   若企业点y值在当前边界点y值之间,则认为是相交的
          if (element.x > latMin && element.x < latMax) {
            // 更新相交计数
            count++;
            // 将当前边界点与前一边界点保存
            points.push([rangePoints[i], rangePoints[i + 1]]);
          }
        }
        // 若与边界无相交则跳过此企业
        if (count != 0) {
          let right = 0;
          let left = 0;
          points.forEach((point) => {
            let x = boundaryFunction(point, element.x);
            x > element.y ? right++ : left++;
          });
          //   console.log(right, left);
          //  奇数偶数判断,若左右皆奇数则认为在选区内
          if (right % 2 != 0 && left % 2 != 0) {
            borderIntersect = true;
          }
        }
      });
      return borderIntersect;
    }

    //  求算边界线函数,根据边界函数求算相交点的x值
    function boundaryFunction(boundary, y) {
      // console.log(arguments);
      let point1 = {
        x: boundary[0][1],
        y: boundary[0][0],
      };
      let point2 = {
        x: boundary[1][1],
        y: boundary[1][0],
      };
      let top = point2.x * (y - point1.y) + point1.x * (point2.y - y);
      let bottom = point2.y - point1.y;
      let x = top / bottom;
      return x;
    }

    // 点与线相交
    function intersectPolyline(click, polylines) {
      // console.log(click, polylines);
      let flag = false;
      // 遍历线段集合
      try {
        polylines.forEach((polyline) => {
          // 求线段四至
          let minx = 9999999,
            miny = 999999,
            maxx = 0,
            maxy = 0;
          polyline.forEach((point) => {
            if (point[0] < minx) minx = point[0];
            if (point[1] < miny) miny = point[1];
            if (point[0] > maxx) maxx = point[0];
            if (point[1] > maxy) maxy = point[1];
          });
          // console.log(minx, miny, maxx, maxy);
          // 判断是否在四至内
          if (
            !(
              click[0] < minx ||
              click[0] > maxx ||
              click[1] < miny ||
              click[1] > maxy
            )
          ) {
            // 求算理想y值
            let y =
              ((click[0] - polyline[0][0]) /
                (polyline[1][0] - polyline[0][0])) *
                (polyline[1][1] - polyline[0][1]) +
              polyline[0][1];
            // 比较
            if (Math.abs(y - click[1]) < 0.00001) {
              flag = true;
              // throw new Error("matched");
              // console.log("@@@@");
            }
          }
        });
      } catch (e) {}
      return flag;
    }

    //面图斑识别
    function identifyPolygon(data) {
      // 开启识别
      if (data) {
        ElMessage({
          message: "开启面图层识别",
          type: "success",
          offset: 50,
          duration: 4000,
        });
        identifyPolygonFlag = true;
        // 面识别
        handlerIdentifyPolygon = new Cesium.ScreenSpaceEventHandler(
          scene.canvas
        );
        handlerIdentifyPolygon.setInputAction(function (movement) {
          // 清除旧标识掩膜
          let entities = viewer.entities._entities._array;
          for (let i = 0; i < entities.length; i++) {
            if (entities[i]._name === "识别标识") {
              viewer.entities.remove(entities[i]);
              i--;
            }
          }
          // 获取点击位置笛卡尔坐标
          var position = scene.pickPosition(movement.position);
          if (!position) {
            position = Cesium.Cartesian3.fromDegrees(0, 0, 0);
          }
          scenePosition = position;
          // 从笛卡尔坐标获取经纬度
          var cartographic = Cesium.Cartographic.fromCartesian(position);
          var longitude = Cesium.Math.toDegrees(cartographic.longitude);
          var latitude = Cesium.Math.toDegrees(cartographic.latitude);
          // 点坐标求交图斑面
          let flag = false;
          PolygonShowedList.forEach((json) => {
            json.data.features.forEach((element) => {
              let matchFlag = intersectPolygon(
                { x: longitude, y: latitude },
                element.geometry.rings[0]
              );
              // 匹配成功
              if (matchFlag) {
                ElMessage({
                  message: "面图层识别成功",
                  type: "success",
                  offset: 50,
                  duration: 4000,
                });
                // 传输图斑识别数据
                pubsub.publish("identifyDataShow", element.attributes);
                pubsub.publish("containerShowChange", true);
                // 匹配成功标识
                flag = true;
                // 视角移动
                scene.camera.flyTo({
                  destination: Cesium.Cartesian3.fromDegrees(
                    longitude,
                    latitude,
                    1000
                  ),
                  orientation: {
                    heading: 0,
                    pitch: Cesium.Math.toRadians(-90),
                    roll: 0,
                  },
                  duration: 1.5,
                });
                // 添加标识掩膜
                var points = new Array(0);
                element.geometry.rings[0].forEach((point) => {
                  points.push(point[0]);
                  points.push(point[1]);
                });
                viewer.entities.add({
                  id: element.attributes.FID,
                  name: "识别标识",
                  polygon: {
                    hierarchy: Cesium.Cartesian3.fromDegreesArray(points),
                    material: new Cesium.Color(1.0, 0.0, 0.0, 0.5),
                  },
                });
              }
            });
          });
          // 匹配失败
          if (!flag) {
            ElMessage({
              message: "面图层识别失败",
              type: "error",
              offset: 50,
              duration: 4000,
            });
          }
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
      } else {
        ElMessage({
          message: "关闭面图层识别",
          type: "success",
          offset: 50,
          duration: 4000,
        });
        // 清除旧标识掩膜
        let entities = viewer.entities._entities._array;
        for (let i = 0; i < entities.length; i++) {
          if (entities[i]._name === "识别标识") {
            viewer.entities.remove(entities[i]);
            i--;
          }
        }
        identifyPolygonFlag = false;
        handlerIdentifyPolygon.destroy();
      }
    }

    // 线图斑识别
    function identifyPolyline(data) {
      // 开启识别
      if (data) {
        ElMessage({
          message: "开启线图层识别",
          type: "success",
          offset: 50,
          duration: 4000,
        });
        identifyPolylineFlag = true;
        // 线识别
        handlerIdentifyPolyline = new Cesium.ScreenSpaceEventHandler(
          scene.canvas
        );
        handlerIdentifyPolyline.setInputAction(function (movement) {
          // 清除旧标识掩膜
          let entities = viewer.entities._entities._array;
          for (let i = 0; i < entities.length; i++) {
            if (entities[i]._name === "识别标识") {
              viewer.entities.remove(entities[i]);
              i--;
            }
          }
          // 获取点击位置笛卡尔坐标
          var position = scene.pickPosition(movement.position);
          if (!position) {
            position = Cesium.Cartesian3.fromDegrees(0, 0, 0);
          }
          scenePosition = position;
          // 从笛卡尔坐标获取经纬度
          var cartographic = Cesium.Cartographic.fromCartesian(position);
          var longitude = Cesium.Math.toDegrees(cartographic.longitude);
          var latitude = Cesium.Math.toDegrees(cartographic.latitude);
          // 相交标识
          let flag = false;
          // console.log(PolylineShowedList);
          PolylineShowedList.forEach((json) => {
            json.data.features.forEach((element) => {
              let matchFlag = intersectPolyline(
                [longitude, latitude],
                element.geometry.paths
              );
              // 匹配成功
              if (matchFlag) {
                ElMessage({
                  message: "线图层识别成功",
                  type: "success",
                  offset: 50,
                  duration: 4000,
                });
                console.log(element);
                // 绘制选中标识
                element.geometry.paths.forEach((point) => {
                  let list = [];
                  point.forEach((p) => {
                    list.push(
                      new Cesium.Cartesian3.fromDegrees(p[0], p[1], 2.1)
                    );
                  });
                  viewer.entities.add({
                    name: "识别标识",
                    polyline: {
                      positions: list,
                      width: 3,
                      material: Cesium.Color.fromCssColorString("#029032"),
                    },
                  });
                });
                // 传输图斑识别数据
                pubsub.publish("identifyDataShow", element.attributes);
                pubsub.publish("containerShowChange", true);

                // 匹配成功标识
                flag = true;
                // 视角移动
                scene.camera.flyTo({
                  destination: Cesium.Cartesian3.fromDegrees(
                    longitude,
                    latitude,
                    20
                  ),
                  orientation: {
                    heading: 0,
                    pitch: Cesium.Math.toRadians(-90),
                    roll: 0,
                  },
                  duration: 1.5,
                });
              }
            });
          });
          // 匹配失败
          if (!flag) {
            ElMessage({
              message: "线图层识别失败",
              type: "error",
              offset: 50,
              duration: 4000,
            });
          }
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
      } else {
        ElMessage({
          message: "关闭线图层识别",
          type: "success",
          offset: 50,
          duration: 4000,
        });
        // 清除旧标识掩膜
        let entities = viewer.entities._entities._array;
        for (let i = 0; i < entities.length; i++) {
          if (entities[i]._name === "识别标识") {
            viewer.entities.remove(entities[i]);
            i--;
          }
        }
        identifyPolylineFlag = false;
        handlerIdentifyPolyline.destroy();
      }
    }

    // 添加变压器POI
    function addTransformerPOI(features) {
      transformerList = features;
      features.forEach((feature) => {
        let imgURL = require("../../assets/pic2/icon/" +
          colorList[proxy.colorIndex].split("#")[1] +
          ".png");
        poiIconLabelAdd(
          Number(feature["location_x"]),
          Number(feature["location_y"]),
          feature["变压器名称"],
          colorList[proxy.colorIndex],
          imgURL
        );
      });
      proxy.colorIndex += 1;
    }

    // 变压器POI点选
    function clickTransformer() {
      transformerClick = true;
      handlerTransformer = new Cesium.ScreenSpaceEventHandler(scene.canvas);
      handlerTransformer.setInputAction(function (movement) {
        let pickedLabel = viewer.scene.pick(movement.position);
        let name = "";
        if (!pickedLabel) {
          return;
        } else {
          name = pickedLabel.id._name;
        }
        pickedLabel = pickedLabel.id;
        // console.log(name);
        // 点击billborad才更新
        if (pickedLabel && transformerClick) {
          // 跳转至详细信息
          transformerList.forEach((transformer) => {
            if (transformer["变压器名称"] === name) {
              // console.log(transformer);
              // 匹配楼栋
              buildingJSON.features.forEach((e) => {
                if (e.attributes["OBJECTID"] === transformer["OBJECTID"]) {
                  // 去除网格线
                  pubsub.publish("netChange", { new: false });
                  pubsub.publish("buildingSelected", e);
                  router.push({
                    path: "/buildingSelected",
                  });
                }
              });
              // 匹配变压器
              transformerJSON.features.forEach((e) => {
                if (e.attributes["BYQMC"] === transformer["变压器名称"]) {
                  pubsub.publish("transformerSelected", e);
                  pubsub.publish("buildingSelected", e);
                  router.push({
                    path: "/buildingSelected",
                  });
                }
              });
            }
          });
        }
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    }

    // 十六进制转RGB
    function hexToCesiumColor(hexColor, alpha) {
      return new Cesium.Color(
        parseInt(hexColor.substring(1, 3), 16) / 255,
        parseInt(hexColor.substring(3, 5), 16) / 255,
        parseInt(hexColor.substring(5, 7), 16) / 255,
        alpha
      );
    }

    //  房屋负荷查询
    function houseLoadSearch(isOn) {
      if (isOn) {
        ElMessage({
          message: "房屋负荷查询开启",
          type: "success",
        });
        handlerHouseLoad = new Cesium.ScreenSpaceEventHandler(scene.canvas);
        handlerHouseLoad.setInputAction(function (e) {
          // 获取点击位置笛卡尔坐标
          var position = scene.pickPosition(e.position);
          // 从笛卡尔坐标获取经纬度
          var cartographic = Cesium.Cartographic.fromCartesian(position);
          var longitude = Cesium.Math.toDegrees(cartographic.longitude);
          var latitude = Cesium.Math.toDegrees(cartographic.latitude);
          // console.log(longitude, latitude);
          // 按距离匹配楼栋
          let nearestBuilding = matchByDistance(
            longitude,
            latitude,
            loadCapacityJSON
          );
          // 删除旧标识
          deleteLayer("负荷查询结果");
          // 添加标识
          let imgURL = require("../../assets/pic2/icon/1296db.png");
          poiIconLabelAdd(
            nearestBuilding.attributes["x"],
            nearestBuilding.attributes["y"],
            "负荷查询结果",
            "#1296db",
            imgURL,
            "负荷查询结果",
            30
          );
          // 房屋属性传输
          pubsub.publish("loadHouseData", nearestBuilding);
        }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
      } else {
        // 删除旧标识
        let entities = viewer.entities._entities._array;
        let flag = false;
        for (let i = 0; i < entities.length; i++) {
          if (
            entities[i]._name != undefined &&
            entities[i]._name.indexOf("负荷查询结果") != -1
          ) {
            viewer.entities.remove(entities[i]);
            i--;
            flag = true;
          }
        }
        if (flag) handlerHouseLoad.destroy();
      }
    }

    return {
      close,
    };
  },
  beforeDestroy() {
    this.subList.forEach((element) => {
      pubsub.unsubscribe(element);
    });
  },
  beforeRouteLeave() {
    this.subList.forEach((element) => {
      pubsub.unsubscribe(element);
    });
  },
};
</script>

<style lang="less" scoped>
#cesiumContainer {
  width: 100%;
  height: 100%;
  overflow: hidden;
}
a {
  display: none !important;
}

.bubble {
  background-color: rgba(6, 19, 31, 0.6);
  background-image: ~"url(@{app-images-root}/content_bg3.png)";
  background-size: 100% 100%;
  width: 420px;
  height: 280px;
  position: absolute;
  top: 50%;
  z-index: 10000;
  font-size: 170%;
  font-weight: bold;
  padding: 0% 0.2%;
  > .closePopup {
    display: inline-block;
    border: transparent;
    outline: none;
    background-color: transparent;
    width: 10%;
    height: 5%;
    position: relative;
    z-index: 10000;
    top: 2%;
    left: 88%;
    font-size: 150%;
  }
  > .el-table {
    margin-top: -8%;
    font-size: 70%;
    text-align: center;
  }
}

button {
  position: absolute;
  bottom: 2%;
  left: 35%;
  outline: none;
  border-radius: 5px;
  border: none;
  background-color: #16a7f5;
  color: white;
  width: 30%;
  height: 50px;
  font-weight: bold;
  font-size: 120%;
  display: block;
}

.fade-enter-active {
  transition: all 1s ease-out;
}

.fade-leave-active {
  transition: all 1s cubic-bezier(1, 0.5, 0.3, 1);
  transform: translateY(-50%);
}

.fade-enter-from,
.fade-leave-to {
  transition: 1s;
  transform: translateY(50%);
  opacity: 0;
}
</style>